# -*- coding: utf-8 -*-
# File Name： register
# Description :
# Author : lirui
# create_date： 2022/6/3
# Change Activity:
from ...misc.dict_wrapper import Dict
from ...misc.log_util import logger


class Registry:
    """
    Registry for callable.
    """

    def __init__(self, name):
        """

        Args:
            name: registry name.
        """
        self.name = name  # Registry name.
        self.callable_mapping = Dict()

    def contain(self, name):
        """
        check whether name in callable_mapping.

        Args:
            name: callable_name.

        Returns:

        """
        return name in self.callable_mapping

    def add(self, name, value):
        """
        Add a member to this registry.

        Args:
            name: member name.
            value: member obj .


        """
        if self.contain(name):
            raise Exception(f'{name} already exist in Registry {self.name}')
        self.callable_mapping[name] = value
        logger.debug(rf'Add a {value.__name__} to registry {self.name}')

    def get(self, name):
        """

        Args:
            name:

        Returns:

        """
        if not self.contain(name):
            raise Exception(f'{name} not in Registry {self.name}')
        callable_ = self.callable_mapping[name]
        return callable_

    def build(self, name, cfg):
        """
        Build object.

        Args:
            name: name of callable class or function.
            cfg: input parameter of callable class.

        Returns:

        """
        if not self.contain(name):
            raise Exception(f'{name} not in Registry {self.name}')
        callable_ = self.callable_mapping[name]
        return callable_(**cfg)
